package com.ulife.order.components.core.refund.factory;

import com.ulife.base.entities.order.SaleOrderPay;
import com.ulife.base.entities.order.SoRefundBill;
import com.ulife.base.logics.order.SaleOrderPayLogic;
import com.ulife.common.utils.lang.JsonMapper;
import com.ulife.order.api.core.refund.RefundBillStatus;
import com.ulife.order.api.core.refund.RefundStatus;
import com.ulife.order.components.core.platform.RefundRequest;
import com.ulife.order.components.core.platform.RefundResponse;
import com.ulife.order.components.core.platform.RefundResponseCode;
import com.ulife.order.components.core.result.BaseResult;
import com.ulife.order.components.core.result.ResultCode;
import com.ulife.order.service.enumeration.PayStatus;
import com.ulife.order.service.util.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lbq on 2016/05/26.
 * 自动退款
 */
@Component(value = "autoRefundFactory")
public class AutoRefundFactory implements IRefundFactory {

    private static final String APP_ID = "2001";
    private static final String APP_KEY = "ulife2001web";
    private static JsonMapper Json = JsonMapper.nonDefaultMapper();

    @Resource
    SaleOrderPayLogic saleOrderPayLogic;

    @Value("${order.payRefund.Url}")
    String payRefundUrl;

    @Override
    public BaseResult<RefundStatus> processRefund(SoRefundBill soRefundBill,long operator) {
        BaseResult result = new BaseResult();
        SaleOrderPay saleOrderPay = saleOrderPayLogic.get(soRefundBill.getSoPayId());
        if (saleOrderPay == null || saleOrderPay.getStatus() != PayStatus.Success.value()) {
            result.setMessage("支付记录不存在或支付状态不正确");
            return result;
        }
        if(soRefundBill.getStatus() == RefundBillStatus.Finished.value()
                || soRefundBill.getRefundStatus() == RefundStatus.Succeed.value()){
            result.setMessage("退款单据已经完成退款操作");
            result.setCode(ResultCode.Repeat);
            return result;
        }
        //订单号|客户请求流水|银行流水|退款金额
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setAmount(new DecimalFormat("####0.00").format(soRefundBill.getRefundAmount()));
        refundRequest.setMerchantId(APP_ID);
        refundRequest.setOrderId(soRefundBill.getSoNo());
        refundRequest.setPaymentSerialNumber(soRefundBill.getSoPayId().toString());
        refundRequest.setSerialNumber(soRefundBill.getId().toString());
        refundRequest.setBankPaymentSerialNumber(saleOrderPay.getBankSerialNo());
        refundRequest.setSignature(sign(soRefundBill, saleOrderPay));

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("para", Json.toJson(refundRequest)));

        try {
            String requestData = "para=".concat(Json.toJson(refundRequest));
            String strResponse = HttpUtil.httpPost(payRefundUrl, requestData, Charset.forName("utf-8"), "application/x-www-form-urlencoded");
            RefundResponse refundResponse = Json.fromJson(strResponse, RefundResponse.class);
            if (refundResponse.getCode() == RefundResponseCode.Success.value()
                    || refundResponse.getCode() == RefundResponseCode.Repeat.value()) {
                result.setData(RefundStatus.Succeed);
                result.setCode(ResultCode.Success);
                //您的订单退款X元已退款到您的余额/微信/支付宝（注：这里显示实际退款方式）账号，请注意查收。如有问题请致电400-687-909
                result.setMessage("您的订单退款"
                        .concat(refundRequest.getAmount())
                        .concat("元已退款到您的")
                        .concat(saleOrderPay.getPayChannel())
                        .concat("账号，请注意查收。如有问题请致电400-687-909"));
                return result;
            }else{
                result.setMessage(refundResponse.getErrorMsg());
            }
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 请求签名
     * @param saleOrderPay
     * @return
     */
    public String sign(SoRefundBill soRefundBill,SaleOrderPay saleOrderPay){

        StringBuffer signature = new StringBuffer();
        signature
                .append("AMOUNT").append("=").append(new DecimalFormat("####0.00").format(soRefundBill.getRefundAmount())).append("&")
                .append("BANKPAYMENTSERIALNUMBER").append("=").append(saleOrderPay.getBankSerialNo()).append("&")
                .append("MERCHANTID").append("=").append(APP_ID).append("&")
                .append("ORDERID").append("=").append(soRefundBill.getSoNo()).append("&")
                .append("PAYMENTSERIALNUMBER").append("=").append(soRefundBill.getSoPayId()).append("&")
                .append("SERIALNUMBER").append("=").append(soRefundBill.getId()).append("&")
                .append("KEY").append("=").append(APP_KEY);

        return DigestUtils.md5Hex(signature.toString());
    }
}
